package com.service.tools.componets;

import com.service.tools.entity.ToolUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class JwtTokenUtil {

    private String secret = "mySecretKey";

    /**
     * 为 ToolUser 生成 JWT token
     */
    public String generateToken(ToolUser user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        claims.put("userName", user.getUserName());
        return createToken(claims, String.valueOf(user.getId()));
    }

    private String createToken(Map<String, Object> claims, String subject) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                // 不设置过期时间，生成无时间限制的token
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 从 token 中获取用户ID
     */
    public Integer getUserIdFromToken(String token) {
        String userId = getClaimFromToken(token, Claims::getSubject);
        return Integer.valueOf(userId);
    }

    /**
     * 从 token 中获取用户名
     */
    public String getUserNameFromToken(String token) {
        Claims claims = getAllClaimsFromToken(token);
        return (String) claims.get("userName");
    }

    /**
     * 从 token 中获取用户信息
     */
    public ToolUser getUserFromToken(String token) {
        Claims claims = getAllClaimsFromToken(token);
        ToolUser user = new ToolUser();
        user.setId(Integer.valueOf(claims.getSubject()));
        user.setUserName((String) claims.get("userName"));
        return user;
    }

    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    /**
     * 验证 token 是否有效
     */
    public Boolean validateToken(String token, ToolUser user) {
        final Integer userId = getUserIdFromToken(token);
        return (userId.equals(user.getId()));
    }
}
